package me.shurufa.fragments;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.adapter.NewMyAdapter;
import me.shurufa.bean.Book;
import me.shurufa.controller.CounterController;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.HeaderWithSearchBar;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.floatingactionbutton.FloatingActionButton;
import me.shurufa.widget.floatingactionbutton.FloatingActionsMenu;
import me.shurufa.widget.functionpopup.FunctionPopup;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.HeaderSpanSizeLookup;

/**
 * 作者 : andy
 * 日期 : 16/3/8 17:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 我的书评Fragment
 */
public class NewMyCommentFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.tv_header_title)
    TextView tv_header_title;

    @Bind(R.id.left_text)
    TextView leftText;

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.header_with_search)
    HeaderWithSearchBar header_with_search;

    // @Bind(R.id.fab)
    // FloatingActionButton mFab;

    @Bind(R.id.fab_menu)
    FloatingActionsMenu mFabMenu;

    @Bind(R.id.fab_add_digest)
    FloatingActionButton mFabAddDigset;

    @Bind(R.id.fab_add_notebook)
    FloatingActionButton mFabAddNotebook;

    @Bind(R.id.ll_overlay)
    LinearLayout mOverlayLayout;

    private Handler mHandler = new Handler();

    private String pageFrom;
    private FunctionPopup mFuncPopup;
    private ArrayList<Book> dataList;
    private NewMyAdapter mostDigestAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;
    private String mSearchContent = "";  // 搜索内容

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_book_comment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != header_with_search) {
            header_with_search.reset();
        }
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();
        dataList = new ArrayList<Book>();
        mostDigestAdapter = new NewMyAdapter(this, dataList, Constants.TYPE_FROM_MY_COMMENT);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mostDigestAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);

        tv_header_title.setText(R.string.header_my_commented);

        //setLayoutManager
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), manager.getSpanCount()));
        recyclerView.setLayoutManager(manager);
        recyclerView.addOnScrollListener(mOnScrollListener);

        backInToolbar.setVisibility(View.GONE);
        leftText.setVisibility(View.VISIBLE);
        rightText.setVisibility(View.GONE);
        leftText.setText(getString(R.string.new_build));
        rightText.setText(getString(R.string.go_discover));
        leftText.setOnClickListener(this);
        rightText.setOnClickListener(this);
        // mFab.setOnClickListener(this);
        // mFab.attachToRecyclerView(recyclerView);

        header_with_search.setOnSearchListener(new HeaderWithSearchBar.OnSearchListener() {
            @Override
            public void onSearch(String content) {
                mSearchContent = content;
                refresh();
            }

            @Override
            public void onBack() {
                mSearchContent = "";
                refresh();
            }
        });

        mOverlayLayout.setOnClickListener(this);
        mFabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
            @Override
            public void onMenuExpanded() {
                startOverlayAnimIn();
            }

            @Override
            public void onMenuCollapsed() {
                startOverlayAnimOut();
            }
        });
        mFabAddDigset.setOnClickListener(this);
        mFabAddNotebook.setOnClickListener(this);

    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(pageFrom, true);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            resetSearchBar();
        }
    };

    public void resetSearchBar() {
        if (header_with_search.getEditText().isFocused()) {
            header_with_search.reset();
            Utils.closeInputMethod(getActivity(), header_with_search.getEditText());
        }
    }

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }


//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage = 1;
        pageFrom = "";
        loadData(pageFrom, true);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(pageFrom, true);
        }
    };


    protected void loadData(final String page, final boolean isDesc) {
        /*if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<NewBookListResponse>(NewBookListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("pageFrom", page == null ? "" : page);
                    params.put("pageDirection", isDesc ? Constants.DESC : Constants.ASC);
                    params.put("pageSize", Constants.PAGE_REQUEST_COUNT);
                    params.put("keyword", mSearchContent);
                    return HttpUtil.post(API.GET_MY_COMMENT, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }

                @Override
                protected void onSuccess(NewBookListResponse result) {
                    pageFrom = result.page;
                    //没有更多数据 不能加载更多
                    if (result.data == null || result.data.length == 0) {
                        if ("".equals(page)) {
                            Utils.showToast("还没有收藏过书摘");
                        }
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                    } else {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        hasMore = true;
                        mPage++;
                        bindData(result, TextUtils.isEmpty(page));
                    }
                    mSearchContent = "";
                }
            }.start();
        }*/
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX,0);
                EventBus.getDefault().post(intent);
                break;
            case R.id.ll_overlay:
                if (mFabMenu.isExpanded()) {
                    startOverlayAnimOut();
                    mFabMenu.collapse();
                }
                break;

            case R.id.fab_add_digest:
                mFabMenu.collapse();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new Intent(Constants.EVENT_MAIN_MENU_ADD_DIGEST));
                    }
                }, 300);

                break;
            case R.id.fab_add_notebook:
                mFabMenu.collapse();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new Intent(Constants.EVENT_MAIN_MENU_ADD_NOTEBOOK));
                    }
                }, 300);

                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction()==Constants.ACTION_SHELVES_FAVOURITE){
        }else if (intent.getAction()==Constants.ACTION_BOOKSHELVES_REFRESH
                ||intent.getAction()==Constants.ACTION_ADD_DIGEST_COMPLETE){
            refresh();
        }

        if (Constants.EVENT_CLOSE_INPUT.equals(intent.getAction())) {
            Utils.closeInputMethod(getActivity(), header_with_search.getEditText());
        }

        if (Constants.EVENT_SEND_BOOK_COMMENT.equals(intent.getAction())) {
            int bookId = intent.getIntExtra(Constants.ARG_BOOK_ID, 0);
            CounterController counterController = new CounterController(mostDigestAdapter, dataList, bookId, CounterController.CounterType.BOOKCOMMENT);
            counterController.handleAddCounter();
        }

        // 删除书评了
        if (Constants.EVENT_DEL_BOOK_COMMENT.equals(intent.getAction())) {
            int bookId = intent.getIntExtra(Constants.ARG_BOOK_ID, 0);
            CounterController counterController = new CounterController(mostDigestAdapter, dataList, bookId, CounterController.CounterType.BOOKCOMMENT);
            counterController.handleDelCounter();
        }

    }

    private void startOverlayAnimIn() {
        mOverlayLayout.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(mOverlayLayout, "alpha", 0.0f, 1.0f);
        animator.setDuration(150);
        animator.start();
    }

    private void startOverlayAnimOut() {

        ObjectAnimator animator = ObjectAnimator.ofFloat(mOverlayLayout, "alpha", 1.0f, 0f);
        animator.setDuration(150);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mOverlayLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }
}
